package org.groovyflow.spring.web;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.groovyflow.GroovyFlowContext;

public class ControllerScope {
	public static final String PREFIX = "SessionObj";

	public static LinkedHashMap getCtrlrScopedSess(HttpServletRequest req){
		String sessionObjKey = GroovyFlowContext.get(AbstractDynamicFinder.CTRLR_CLASSNAME) + PREFIX;
		LinkedHashMap map = (LinkedHashMap) req.getSession().getAttribute(sessionObjKey);
		if(map == null){
			map = new LinkedHashMap();
		}
		//Put the map in the session.
		req.getSession().setAttribute(sessionObjKey, map);
		return map;
	}


   public static void clearSession(HttpServletRequest req) {
	   HttpSession sess = req.getSession();
	   Enumeration namesEnum = sess.getAttributeNames();
	   Set<String> names = new HashSet<String>();
	   while(namesEnum.hasMoreElements()){
		  String name = (String) namesEnum.nextElement();
		  //TODO  Need constant!
		  if(name.endsWith(PREFIX)){
			  names.add(name);
		  }
	   }
	   for(String name : names){
		   String conrollerClassName = (String) GroovyFlowContext.get(AbstractDynamicFinder.CTRLR_CLASSNAME);
		   if( ! name.startsWith(conrollerClassName)){
			   sess.removeAttribute(name);
			   System.out.println("Removed " + name + " from sesson.");
		   }
	   }

	}


}
